<template>
  <div id="app">
    <router-view />
  </div>
</template>

<script>
import { mapMutations } from "vuex";
import { getUserInfo } from '@/api/userApi';
export default {
  name: "App",
  data() {
    return {
      active: 0,
    };
  },
  created() {
    // 判断用户token是否有效
    this.authenticationToken();
    // 判断存储在localStorage中的购物车数据是否有效
    this.authenticationshopCar();
  },
  methods: {
    ...mapMutations("m_user", [
      "changeHavingLogin",
      "setUserInfo",
      "setBillList",
    ]),
    async authenticationToken() {
      let res = await getUserInfo();
      if(res.code === 200) {
        this.setUserInfo(res.data);
        let newToken = this.$jwt.sign(res.data, this.$appConfig.jwt_secret, {
          expiresIn: "1day",
        });
        localStorage.setItem("token", newToken);
        this.changeHavingLogin(true); // 登录成功
      } else {
        // 说明未登录, 清空相关数据
        localStorage.removeItem("token");
        this.setUserInfo({});
        this.changeHavingLogin(false);
      }
    },
    authenticationshopCar() {
      let shopCar = localStorage.getItem("shopCar");
      if (shopCar) {
        this.$jwt.verify(shopCar, this.$appConfig.jwt_secret, (err, result) => {
          if (!err) {
            this.setBillList(result.bill);
          }
        });
      }
    },
  },
};
</script>

<style lang="scss">
img {
  width: 100%;
  height: 100%;
}
h1,
h2,
h3,
h4,
h5,
h6,
p {
  margin: 0;
  padding: 0;
}
li {
  list-style: none;
}
a {
  text-decoration: none;
}
* {
  box-sizing: border-box;
}
</style>
